import { ComUtils } from "@/utils/Com"
import { For, Accessor, Show, Switch, Match, createSignal } from "solid-js"
import Popup from "./Popup"
interface Page {
    page: number
    totalPages: number
}
type TableSlots = { [key: string]: any }
interface Props {
    items: Accessor<any[]>
    page: Accessor<Page>
    changePage?: (page: number) => void
    deleteItem?: (item: any) => void
    editItem?: (item: any) => void
    detail?: (item: any) => void
    fields?: string[]
    opration?: string[]
    hideFields?: string[]
    oprationIcons?: string[]
    onFieldClick?: (item: any, k: any) => void
    slots?: TableSlots
}
const leftIcon = ComUtils.getResourceUrl('/icons/left.svg')
const rightIcon = ComUtils.getResourceUrl('/icons/right.svg')
export default function CustomTable(props: Props) {
    const [deletePopup, setDeletePopup] = createSignal(false)
    const [currentItem, setCurrentItem] = createSignal()
    const getCols = (opration = false) => {
        let cols: any[] = []
        if (props.items().length > 0) {
            cols = Reflect.ownKeys(props.items()[0])
        } else {
            cols = []
        }
        if (props.hideFields) {
            cols = cols.filter(k => !props.hideFields?.includes(String(k)))
        }
        if (cols.length > 0 && opration) {
            cols.push('opration')
        }
        return cols
    }
    const getVal = (val: any, k: string | symbol) => {
        if (typeof val !== 'object' || val == null || val === undefined) {
            return val
        }
        const v = Reflect.get(val, k)
        if (typeof v === 'undefined' || (typeof v === 'string' && v.trim() === '')) {
            return '---'
        } if (typeof v === 'boolean') {
            return v ? 'YES' : 'NO'
        } else {
            return v
        }
    }

    const onDieldClick = (item: any, k: any) => {
        if (!props.fields?.includes(k)) {
            return
        }
        props.onFieldClick?.(item, k)
    }

    const showDelete = (item: any) => {
        setCurrentItem(item)
        setDeletePopup(true)
    }

    const deleteItem = () => {
        props.deleteItem?.(currentItem())
        setDeletePopup(false)
    }

    const changePage = (t = 1) => {
        if (t == 1 && props.page().page < props.page().totalPages - 1) {
            props.changePage?.(props.page().page + 1)
        } else if (t != 1 && props.page().page > 0) {
            props.changePage?.(props.page().page - 1)
        }
    }

    const TableItem = (props: { item: any, k: any }) => {
        const { item, k } = props
        return <td onclick={() => onDieldClick(item, k)}>

            <Switch fallback={<div class="p-2 max-w-[8rem] whitespace-nowrap overflow-hidden text-ellipsis" title={getVal(item, k)}>
                {getVal(item, k)}
            </div>}>
                <Match when={/(time|date)/i.test(String(k))}>
                    <div class="max-w-[8rem]" title={ComUtils.formatDate(getVal(item, k))}>
                        {ComUtils.formatDate(getVal(item, k),false,true)}
                    </div>
                </Match>
                <Match when={typeof getVal(item, k) === 'object' && getVal(item, k)?.length}>
                    {
                        getVal(item, k).map((obj: string, kk: any) => <TableItem item={obj} k={kk} />)
                    }
                </Match>
                <Match when={/^https?:\/\/.*\.(jpg|jpeg|gif|png|webp|avif|ico)/i.test(String(getVal(item, k)))}>
                    <a href={getVal(item, k)} target="_blank" rel="noopener noreferrer">
                        <img class="block w-16 max-w-none m-auto p-2" src={getVal(item, k)} alt="img" />
                    </a>
                </Match>
                <Match when={/^https?:\/\//i.test(String(getVal(item, k)))}>
                    <a class=" underline text-blue-500" href={getVal(item, k)} target="_blank">
                        link
                    </a>
                </Match>
            </Switch>

        </td>
    }

    return <div class="w-full overflow-auto">
        <table class=" w-full text-sm">
            <thead class=" sticky top-0">
                <tr class=" font-bold text-gray-400">
                    <For each={getCols(true)}>
                        {
                            k => <td>
                                <div class="p-2">
                                    {
                                        k as any
                                    }
                                </div>
                            </td>
                        }
                    </For>
                </tr>
            </thead>
            <tbody>
                <For each={props.items()}>
                    {
                        item => <tr class=" hover:bg-[#1f2125]">
                            <For each={getCols()}>
                                {
                                    k => <TableItem item={item} k={k} />
                                }
                            </For>
                            <td class=" sticky right-0 ">
                                <div class="flex gap-3">
                                    <Show when={props.deleteItem}>
                                        <button onclick={() => showDelete(item)}>
                                            <img class="w-5 h-5" src={props.oprationIcons?.[0]} alt="delete" />
                                        </button>
                                    </Show>
                                    <Show when={props.editItem}>
                                        <button onclick={() => props.editItem?.(item)}>
                                            <img class="w-5 h-5" src={props.oprationIcons?.[1]} alt="delete" />
                                        </button>
                                    </Show>
                                    <Show when={props.detail}>
                                        <button onclick={() => props.detail?.(item)}>
                                            <img class="w-5 h-5" src={props.oprationIcons?.[2]} alt="delete" />
                                        </button>
                                    </Show>
                                </div>
                            </td>
                        </tr>
                    }
                </For>
            </tbody>
        </table>
        <div class="flex items-center justify-center gap-4 sticky bottom-0 left-0">
            <span class="text-slate-500">
                page {props.page().page + 1}/{props.page().totalPages}
            </span>

            <Show when={props.page().page > 0}>
                <button onclick={() => changePage(0)}>
                    <img class="w-5 h-5" src={leftIcon} alt="leftIcon" />
                </button>
            </Show>
            <Show when={props.page().page < props.page().totalPages - 1}>
                <button onclick={() => changePage(1)}>
                    <img class="w-5 h-5" src={rightIcon} alt="rightIcon" />
                </button>
            </Show>

        </div>
        <Popup show={deletePopup} title="warning" close={() => setDeletePopup(false)} ok={deleteItem}>
            <h3>Are you sure you want to delete this item?</h3>
        </Popup>
    </div>
}